package com.keensense.vcm;

import static com.keensense.vcm.VCMErrorCode.SUCCESS;
import static com.keensense.vcm.VCMErrorCode.USER_NOT_LOGIN;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import com.keensense.vcm.common.utils.ExceptionFactory;
import com.keensense.vcm.common.utils.LogUtils;
import com.keensense.vcm.model.BaseResponse;
import com.keensense.vcm.model.VCMResponse;

/**
 * @author lanjian
 * @date 2020/5/6 11:18 上午
 */
public class DynamicProxy implements InvocationHandler {

    /**
     * 需要代理的目标类
     */
    private Object target;

    private Object obj = new Object();

    public Object bind(Object target) {
        this.target = target;
        return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        BaseResponse response = null;
        boolean loggedIn = false;
        while (!loggedIn) {
            response = (BaseResponse) method.invoke(target, args);
            if (!SUCCESS.equals(response.getResult().getCode())) {
                LogUtils.getLog().error("errorCode=" + response.getResult().getCode() + ",errorMsg=" + response.getResult().getErrMsg());
            }
            synchronized (obj) {
                if (USER_NOT_LOGIN.equals(response.getResult().getCode())) {
                    VCM vcm = (VCM) target;
                    VCMResponse vcmResponse = vcm.login();
                    if (SUCCESS.equals(vcmResponse.getResult().getCode())) {
                        LogUtils.getLog().info("登录成功");
                    } else {
                        LogUtils.getLog().info("登录失败");
                    }
                } else {
                    loggedIn = true;
                }
            }
        }
        return response;
    }
}
